// functionPage/pages/experienceDetail/experienceDetail.js
const app = getApp();
import { giveLikeApi, hasPermission } from '../../../utils/tools';
import Http from '../../../utils/http.js';
const http = new Http();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        navbtn: '', //navbtn  01--操作记录进入-显示顶部导航
        isIphone: false,
        scrollToView: false,
        experienceTypeName: '',
        city: '',
        country: '',
        lat: '',
        lng: '',
        extypeid: '',
        createuid: '',
        realnapicurl: '',
        realname: '',
        createtime: '',
        sceneImageArr: [],
        address: '',
        content: '',
        excellentflg: '00',
        title: '',
        //评论
        toView: '', //跳转留言id
        commentTop: 101,
        remarkEdit: false,
        tocommentid: '', //被回复的评论id,回复时传
        remarkValue: '', //评论/回复内容
        placeHoldComment: '欢迎留言讨论', //评论/回复内容
        touid: '',
        toreplyid: '',
        privateflg: '00',
        commentList: [],
        commentcount: 0,
        // 编辑相关
        show: false,
        actions: [
            {
                name: '编辑',
                color: '#333333',
                id: 2,
            },
            {
                name: '删除',
                color: '#FF455E',
                id: 1,
            },
        ],
        // 经验相关
        id: '',
        // 当前经验创建人id
        activeCreateUid: '',
        // 点赞相关
        // 默认不点赞
        praiseflg: '00',
        praisecnt: 0,
        // 评论id
        remarkId: '',
        permissionList: ['00', '01'],
        // 团长/副团长
        authority: '',
        review: '',
        anonymous: false, //评论匿名
    },
    // 查看他人主页
    jumpOthersPage(e) {
        wx.navigateTo({
            url: `/functionPage/pages/othersHomePage/othersHomePage?uid=${e.currentTarget.dataset.uid}`,
        });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let _that = this;
        wx.getSystemInfo({
            success: function (res) {
                let isIpx;
                //model中包含着设备信息
                var model = res.model;
                if (model.search('iPhone') != -1) {
                    isIpx = true;
                } else {
                    isIpx = false;
                }
                _that.setData({
                    isIphone: isIpx,
                });
            },
        });
        if (options.id) {
            _that.setData({
                id: options.id,
            });
            _that.getExperienceDetail(options.id);
        }
        if (options.comment) {
            _that.setData({
                scrollToView: true,
            });
        }

        _that.setData({
            review: options.review || '',
            navbtn: options.navbtn, //navbtn  01--操作记录进入
        });
    },

    onShow() {
        if (this.data.experienceTypeName) {
            wx.setNavigationBarTitle({
                title: this.data.experienceTypeName,
            });
        }
    },
    onReady() {
        this.footComment = this.selectComponent('#foot-comment');
    },
    // 查询经验详情
    getExperienceDetail(id) {
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + 'cjMap/getExperienceDetail',
            data: {
                authId: app.globalData.authId,
                id,
            },
            success: function (res) {
                let { experience } = res.data;
                _that.setData(
                    {
                        experienceTypeName: experience.typename,
                        city: experience.city,
                        country: experience.country,
                        lat: experience.lat,
                        lng: experience.lng,
                        extypeid: experience.extypeid,
                        sceneImageArr: experience.picurls,
                        realnapicurl: experience.realnapicurl,
                        realname: experience.realname,
                        createuid: experience.createuid,
                        createtime: app.timeago(experience.createtime),
                        address: experience.address,
                        content: experience.content,
                        excellentflg: experience.excellentflg,
                        title: experience.title || '',
                        praiseflg: experience.praiseflg,
                        praisecnt: experience.praisecnt,
                        commentList: experience.commentList,
                        commentcount: experience.commentcount,
                        authority: experience.authority,
                    },
                    () => {
                        wx.setNavigationBarTitle({
                            title: experience.typename,
                        });
                        if (_that.data.scrollToView) {
                            _that.setData({
                                toView: 'comment',
                                commentTop: 0,
                            });
                            _that.setData({
                                scrollToView: false,
                            });
                        }
                    }
                );
            },
        });
    },

    // 导航
    navigate() {
        let _that = this;
        wx.openLocation({
            latitude: _that.data.lat,
            longitude: _that.data.lng,
            name: '详细地址',
            address: _that.data.address,
        });
    },

    // 预览图片
    previewImage(e) {
        let index = e.currentTarget.dataset.index;
        wx.previewImage({
            current: this.data.sceneImageArr[index],
            urls: this.data.sceneImageArr,
        });
    },

    //评论
    jumpOrRemark(e) {
        if (this.data.commentTop > 100) {
            this.setData({
                toView: 'comment',
                commentTop: 0,
            });
        }
        if (e.detail.setplaceHold == '00') {
            this.footComment.articalRemark();
            this.onResetInputContent();
        }
    },

    // 重置输入框内容
    onResetInputContent() {
        this.setData({
            placeHoldComment: '欢迎留言讨论',
            tocommentid: '',
            touid: this.data.createuid,
            privateflg: '00',
        });
    },

    scrollTopFun(e) {},

    remarkInfo(e) {
        let _that = this;
        _that.footComment.remarkFocus('01');
        let name = e.detail.battleTag;
        _that.setData({
            tocommentid: e.detail.contentid || e.detail.tocommentid, //被回复的评论id,回复时传
            placeHoldComment: '@' + name, //评论/回复内容
            touid: e.detail.touid,
            toreplyid: e.detail.toreplyid,
            privateflg: e.detail.privateflg,
        });
    },
    remarkEditChange(e) {
        this.setData({
            remarkEdit: e.detail.remarkEdit, //被回复的评论id,回复时传
        });
    },

    // 编辑
    edit(e) {
        let { createuid, excellentflg, authority } = e.currentTarget.dataset;
        let actions = [
            {
                name: '编辑',
                color: '#333333',
                id: 2,
            },
            {
                name: '删除',
                color: '#FF455E',
                id: 1,
            },
        ];

        if (hasPermission(this.data.permissionList) || authority) {
            if (excellentflg === '00') {
                actions.splice(0, 0, {
                    name: '设置为精华',
                    color: '#333333',
                    id: 3,
                });
            } else {
                actions.splice(0, 0, {
                    name: '取消精华',
                    color: '#333333',
                    id: 4,
                });
            }
        }

        this.setData({
            show: true,
            activeCreateUid: createuid,
            actions,
        });

        // 导航栏置灰
        wx.setNavigationBarColor({
            frontColor: '#000000',
            backgroundColor: '#484848',
            animation: {
                duration: 300,
                timingFunc: 'easeIn',
            },
        });
    },

    // 取消编辑
    onCancel() {
        // 导航栏置白
        wx.setNavigationBarColor({
            frontColor: '#000000',
            backgroundColor: '#ffffff',
            animation: {
                duration: 300,
                timingFunc: 'easeIn',
            },
        });
        this.setData({
            show: false,
        });
    },

    // 选中后
    onSelect(e) {
        console.log(e);
        let _that = this;
        if (e.detail.id == 2) {
            _that.onCancel();
            // 再次编辑都是默认type 01
            wx.navigateTo({
                url: `../../../releasePage/pages/addExperience/addExperience?type=01&id=${_that.data.id}&current=1&detail=01`,
            });
        } else if (e.detail.id == 1) {
            wx.showModal({
                title: '提示',
                content: '确认要删除该项吗？',
                success: function (res) {
                    if (res.confirm) {
                        _that.deleteExperience();
                    } else {
                        console.log('点击取消回调');
                    }
                },
            });
        } else if (e.detail.id == 3) {
            _that.setExperienceExcellent('01');
        } else if (e.detail.id == 4) {
            _that.setExperienceExcellent('00');
        } else if (e.detail.value == 'remark-delete') {
            wx.showModal({
                title: '提示',
                content: '确认要删除该项吗？',
                success: function (res) {
                    if (res.confirm) {
                        _that.onCancel();
                        _that.handleDeleteRemark();
                    } else {
                        _that.onCancel();
                        console.log('点击取消回调');
                    }
                },
            });
        }
    },

    refresh() {
        this.getExperienceDetail(this.data.id);
    },

    deleteExperience() {
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + `cjMap/deleteExperience`,
            method: 'GET',
            header: {
                'content-type': 'application/x-www-form-urlencoded',
            },
            data: {
                authId: app.globalData.authId,
                id: _that.data.id,
            },
            success: function (res) {
                if (res.data.status === '0') {
                    app.globalData.expRefresh = true;
                    app.globalData.indexExpRefresh = true;

                    _that.onCancel();
                    let pages = getCurrentPages(); //当前页面栈

                    let prevPage = pages[pages.length - 2];
                    if (prevPage && typeof prevPage.refresh == 'function') {
                        prevPage.refresh();
                    }

                    let prevPage2 = pages[pages.length - 3];
                    if (prevPage2 && typeof prevPage2.refresh == 'function') {
                        prevPage2.refresh();
                    }

                    let prevPage3 = pages[pages.length - 4];
                    if (prevPage3 && typeof prevPage3.refresh == 'function') {
                        prevPage3.refresh();
                    }

                    wx.showToast({
                        title: '删除成功',
                        icon: 'success',
                        duration: 1500,
                    });
                    setTimeout(function () {
                        wx.navigateBack({
                            delta: 1,
                        });
                    }, 2000);
                }
            },
        });
    },

    // 设为精华和取消精华
    setExperienceExcellent(excellentflg) {
        let _that = this;
        wx.request({
            url:
                app.globalData.rootPath +
                `cjMap/setExperienceExcellent?authId=${app.globalData.authId}`,
            header: {
                'content-type': 'application/json',
            },
            data: {
                excellentflg,
                id: _that.data.id,
            },
            success: function (res) {
                if (res.data.status == '0') {
                    _that.getExperienceDetail(_that.data.id);
                    app.globalData.expRefresh = true;

                    _that.onCancel();
                    let pages = getCurrentPages(); //当前页面栈

                    let prevPage = pages[pages.length - 2];
                    if (prevPage && typeof prevPage.refresh == 'function') {
                        prevPage.refresh();
                    }

                    let prevPage2 = pages[pages.length - 3];
                    if (prevPage2 && typeof prevPage2.refresh == 'function') {
                        prevPage2.refresh();
                    }

                    let prevPage3 = pages[pages.length - 4];
                    if (prevPage3 && typeof prevPage3.refresh == 'function') {
                        prevPage3.refresh();
                    }
                }
            },
        });
    },

    // 点赞
    handleLike() {
        this.setData(
            {
                praiseflg: this.data.praiseflg == '00' ? '01' : '00',
                praisecnt:
                    this.data.praiseflg == '00'
                        ? this.data.praisecnt + 1
                        : this.data.praisecnt - 1,
            },
            () => {
                let content = this.data.title || this.data.content;
                giveLikeApi(
                    '12',
                    this.data.id,
                    this.data.praiseflg,
                    this.data.createuid,
                    content
                );
                this.update();
            }
        );
    },

    // 同步上层经验点赞
    update() {
        // 简单模拟e
        let e = {
            detail: {
                id: this.data.id,
                praiseflg: this.data.praiseflg,
                praisecnt: this.data.praisecnt,
                typename: this.data.experienceTypeName,
            },
        };
        const pages = getCurrentPages(); //当前页面栈
        const prevPage = pages[pages.length - 2]; //上一页面
        if (typeof prevPage.handleLike == 'function') {
            prevPage.handleLike(e);
        }
    },

    // 刷新上一页面的经验列表的数字
    handleComment() {
        const params = {
            id: this.data.id,
            commentcount: this.data.commentcount,
            typename: this.data.experienceTypeName,
        };
        const pages = getCurrentPages(); //当前页面栈
        const prevPage = pages[pages.length - 2]; //上一页面
        if (typeof prevPage.refreshCommentNum == 'function') {
            prevPage.refreshCommentNum(params);
        }
    },

    //删除评论
    deleteRemark(e) {
        this.setData({
            show: true,
            actions: [
                {
                    name: '删除',
                    value: 'remark-delete',
                    color: '#FF455E',
                },
            ],
            remarkId: e.detail.id,
            activeCreateUid: e.detail.createuid,
        });
    },

    handleDeleteRemark() {
        //评论删除请求
        http.getRequest(
            `cjMap/deleteComment?authId=${app.globalData.authId}&id=${this.data.remarkId}`
        ).then((res) => {
            if (res.status == 0) {
                wx.showToast({
                    title: '删除成功',
                    icon: 'none',
                    duration: 1500,
                });
                this.refreshComment();
            }
        });
    },

    // 刷新本页评论
    refreshComment() {
        let data = {
            authId: app.globalData.authId,
            id: this.data.id,
        };
        http.getRequest(`cjMap/getExperienceDetail`, data).then((res) => {
            if (res.status == 0) {
                let { experience } = res;
                this.setData(
                    {
                        commentList: experience.commentList,
                        commentcount: experience.commentcount,
                        remarkEdit: false,
                        tocommentid: '', //被回复的评论id,回复时传
                        remarkValue: '', //评论/回复内容
                        placeHoldComment: '欢迎留言讨论', //评论/回复内容
                    },
                    () => {
                        this.handleComment();
                    }
                );
            }
        });
    },
});
